package com.jasperframework.boot.common.utils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
  * <p>  </p>
  *
  * @site https://miliqkdoc.motopa.cn/
  * @author daizhao
  * @date 2022/12/12 12:12
  */
public class HmacSHA1Utils {

    /**
     * HmacSHA1 签名算法
     * @param message 待签名的消息
     * @param secret  密钥
     * @return
     */
    public static String getHmacSHA1(String message, String secret){
        String hmac = "";
        try {
            Mac sha1HMAC = Mac.getInstance("HmacSHA1");
            SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA1");
            sha1HMAC.init(secretKey);

            byte[] rawHmac = sha1HMAC.doFinal(message.getBytes(StandardCharsets.UTF_8));
            hmac = bytesToHex(rawHmac);

            System.out.println("HMAC-SHA1: " + hmac);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
        }
        return hmac;
    }

    // 将字节数组转换为十六进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    /**
     　　* 将byte转为16进制 通过BigInteger转换
     　　* @param bytes
     　　* @return
     　　*/
    private static String byte2HexOfBigInteger(byte[] bytes){
        BigInteger bigInt = new BigInteger(1, bytes);
        return bigInt.toString(16);
    }

    /**
     　　* 将字节数组转为16进制，通过Integer字节转换
     　　* @param bytes
     　　* @return
     　　*/
    private static String byte2Hex(byte[] bytes){
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }
}
